<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useUserStore } from '@/stores/user'

const store = useUserStore()
const form = reactive({ oldPwd: '', newPwd: '', confirm: '' })
const formRef = ref()
const loading = reactive({ submitting: false })

const rules = {
  oldPwd: [ { required: true, message: '请输入原密码', trigger: 'blur' } ],
  newPwd: [ { required: true, message: '请输入新密码', trigger: 'blur' }, { min: 6, message: '至少6位', trigger: 'blur' } ],
  confirm: [ { required: true, message: '请确认新密码', trigger: 'blur' }, {
    validator: (_: any, v: string, cb: (e?: Error) => void) => { v !== form.newPwd ? cb(new Error('两次密码不一致')) : cb() }, trigger: 'blur'
  } ]
}

const submit = async () => {
  await formRef.value?.validate(async (valid: boolean) => {
    if (!valid || !store.name) return
    loading.submitting = true
    try {
      store.changePassword(store.name, form.oldPwd, form.newPwd)
      alert('修改成功')
      Object.assign(form, { oldPwd: '', newPwd: '', confirm: '' })
    } catch (e: any) {
      alert(e?.message || '失败')
    } finally {
      loading.submitting = false
    }
  })
}
</script>

<template>
  <div style="padding:16px">
    <el-card>
      <h3>修改密码</h3>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="max-width:480px">
        <el-form-item label="原密码" prop="oldPwd">
          <el-input type="password" v-model="form.oldPwd" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input type="password" v-model="form.newPwd" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirm">
          <el-input type="password" v-model="form.confirm" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading.submitting" :disabled="loading.submitting" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  
</template>

<style scoped>
</style>


